from time import time
from time import sleep
from datetime import datetime

from bootstrap import *

from app import worker
from app.utils import informator

from app.config import USE_PROXY
from app.config import MAX_THREADS
from app.config import SUPPRESS_PROMPT

from app.exceptions import NoLinks
from app.exceptions import ProxyNotFound

from core.models import Link

provider = worker.get_provider() or None
proxy = worker.get_proxy()
links = worker.distribute(use_multiprocess = not use_threads)
use_proxy = USE_PROXY
time_started = time()
data_object = {}

if not links:
    raise NoLinks('There are no links. Please import links first.')

informator(logstr = 'Testing started...')
informator(logstr = 'Time started: %s' % datetime.fromtimestamp(time_started))

informator(logstr = '\n====================\n', color = 'green')

# Check whether proxy enabled or not
# or of proxies available in the system
if not proxy:
    choice = ''

    if not SUPPRESS_PROMPT:
        while choice.lower() not in ['yes', 'no']:
            choice = raw_input('No proxy found, continue? [Yes/No]:')

            if 'yes' in choice.lower() and USE_PROXY:
                informator(logstr = 'Setting [mode: NO_PROXY]...')
                informator(logstr = '\n====================\n', color = 'green')

                sleep(1)

                use_proxy = False
            else:
                raise ProxyNotFound('Proxy not found.')
    else:
        use_proxy = False


if provider:
    informator(logstr = 'Provider: %s' % provider.name)
else:
    informator(logstr = 'Provider: Not recognized')

if use_proxy:
    data_object.setdefault('use_proxy', True)

    informator(logstr = 'Proxy: %s' % proxy.host)
else:
    data_object.setdefault('use_proxy', True)

informator(logstr = 'Total resources to be checked %d' % Link.objects.all().count())

informator(logstr = '\n====================\n', color = 'green')

if not use_threads:
    use_threads = True

data_object.setdefault('links', links)
data_object.setdefault('proxy', proxy.__as_json__())
data_object.setdefault('provider', provider)
data_object.setdefault('use_threads', use_threads)
data_object.setdefault('time_started', time_started)

worker.run(meta = data_object)
